package common

import (
	"gitee.com/go_library/common/log"
	"github.com/labstack/echo"
	"net/http"
)

/**
 * 设定将响应发送给请求端的方式
 */
const (
	MsgSuccess            = "操作成功"
	MsgBindDataFailed     = "绑定参数失败"
	MsgMissingParameter   = "缺少参数"
	MsgInternalCallFailed = "内部调用失败"
)

type Result struct {
	Status  bool        `json:"status"`
	Massage string      `json:"msg"`
	Data    interface{} `json:"data"`
	Code    int         `json:"code"`
}

func (r *Result) Send(c echo.Context) error {
	return c.JSON(http.StatusOK, r)
}

// 拦截路由返回的错误、空响应，转换成正常的响应
func ResultHandler(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		defer func() {
			if err := recover(); err != nil {
				res := HandleError(NewSeriousError(err))
				if c.Response().Size == 0 {
					_ = res.Send(c)
				}
			}
		}()
		err := next(c)
		r := c.Response()
		if r.Size == 0 {
			if err == nil {
				return Success(c)
			} else {
				return HandleError(err).Send(c)
			}
		} else if err != nil {
			log.Err.Println("路由中的处理函数返回了错误，但响应已经发出：", HandleError(err))
		}
		return nil
	}
}

func SuccessData(c echo.Context, data interface{}) error {
	res := &Result{
		Status:  true,
		Massage: MsgSuccess,
		Data:    data,
	}
	return res.Send(c)
}

func Success(c echo.Context, msg ...string) error {
	res := &Result{
		Status:  true,
		Massage: MsgSuccess,
	}
	if len(msg) > 0 {
		res.Massage = msg[0]
	}
	return res.Send(c)
}
